package com.shiyun.disaster_station.config;

import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 类 描 述: 注入配置
 * 作   者: 史云
 * @author 史云
 * 时   间: 2022年02月28日  14:36:00
 */
@MapperScan("com.chengtiexinxi.**.dao")
@Configuration
public class MyBatisPlusConfig {

    @Bean
    public CustomizedSqlInjector customizedSqlInjector() {
        return new CustomizedSqlInjector();
    }

    @Bean
    public GlobalConfig globalConfig(@Qualifier("customizedSqlInjector")CustomizedSqlInjector customizedSqlInjector){
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setSqlInjector(customizedSqlInjector);
        return globalConfig;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource db(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("db")DataSource dataSource,@Qualifier("globalConfig")GlobalConfig globalConfig)throws Exception{
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        // datasource
        factoryBean.setDataSource(dataSource);
        // 访问应用服务器的资源:虚拟文件系统
        factoryBean.setVfs(SpringBootVFS.class);
        factoryBean.setTypeAliasesPackage("com.chengtiexinxi.**.dao");
        // XML文件位置
        Resource[] mapperResources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**.xml");
        factoryBean.setMapperLocations(mapperResources);
        // 其他配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        // Geometry对象映射的拦截器
//        configuration.addInterceptor(new MybatisGeometryHandler());
        // 设置注解返回
        configuration.setUseGeneratedKeys(true);
        factoryBean.setConfiguration(configuration);
        // 配置自定义SQL注入接口
        factoryBean.setGlobalConfig(globalConfig);
        return factoryBean.getObject();
    }
}

